package com.itheima.tliasbackend.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.tliasbackend.exception.GlobalException;
import com.itheima.tliasbackend.mapper.EmpMapper;
import com.itheima.tliasbackend.pojo.Emp;
import com.itheima.tliasbackend.service.EmpService;
import com.itheima.tliasbackend.utils.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

// 员工业务实现类
@Slf4j
@Service
public class EmpServiceImpl implements EmpService {

    @Autowired
    private EmpMapper empMapper;

    @Override
    public PageBean page(String name, Integer gender, LocalDate begin, LocalDate end, Integer page, Integer pageSize) {
        // 分页插件能不能不用，可以！
        PageHelper.startPage(page, pageSize);

        List<Emp> empList = empMapper.selectList(name, gender, begin, end);

        PageInfo<Emp> pageInfo = PageInfo.of(empList);
        // 4. 封装
        return new PageBean(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public void removeByIds(List<Integer> idList) {
        empMapper.deleteByIds(idList);
    }

    @Override
    public void save(Emp emp) {
        // 默认值 不要去依仗数据库 业务中体现出来
        if (Objects.isNull(emp.getPassword())) {
            emp.setPassword("123456");
        }
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.insert(emp);
    }

    @Override
    public Emp getById(Integer id) {
        return empMapper.selectById(id);
    }

    @Override
    public void updateById(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.updateById(emp);
    }

    @Override
    public Emp login(Emp emp) {
        Emp emp1 = empMapper.selectByUsernameAndPassword(emp.getUsername(), emp.getPassword());
        if (emp1 == null) {
            throw new GlobalException("账户或密码错误了");
        }
        return emp1;
    }
}